package osgi;

import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;


public class ContainerListener implements ServletContextListener {
	private static final Log log = LogFactory.getLog(OSGiAdmin.class);
	
	private ServletContext context = null;
	private BundleContext bundleContext = null;
	public void contextInitialized(ServletContextEvent event) {
		this.context = event.getServletContext();
	
		//测试
		OSGITest test = new OSGITest();
		test.setRealPath(this.context.getRealPath("/"));
		//bundleContext = test.run();
		try {
			this.startOsgi();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void startOsgi() throws Exception {
		try {
			String osgiConfigPath = context.getInitParameter("osgiConfig");
			if (osgiConfigPath == null) osgiConfigPath = "/osgi.properties";
			Properties prop = new Properties();
			InputStream is = ContainerListener.class.getResourceAsStream(osgiConfigPath);
			prop.load(is);
			is.close();
			OSGiConfig osgiConfig = new OSGiConfig();
			osgiConfig.load(prop, context);
			
			
			OSGiAdmin.startup(osgiConfig, this.context);
		} catch (Exception e) {
			log.error("启动OSGi框架失败：" + e.getMessage(), e);
			try {
				OSGiAdmin.shutdown();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	public void contextDestroyed(ServletContextEvent event) {
		try {
			OSGiAdmin.shutdown();
		} catch (Exception e) {
			log.error("卸载OSGi框架失败：" + e.getMessage(), e);
		}
		this.context = null;
		bundleContext = null;
	}

}
